//
//  AppDelegate.m
//  LoveAttention
//
//  Created by 鞠超 on 15/12/28.
//  Copyright © 2015年 JC. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"
#import <SMS_SDK/SMSSDK.h>
#import "CommonDef.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "LoginViewController.h"
#import "Pingpp.h"

// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#define SMSapp_Key @"1479418374dec"
#define SMSapp_Secret @"f1a3e45adf72013866e24a5a074e6961"


#define umeng_app_key @"557e958167e58e0b720041ff"

#define UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define _IPHONE80_ 80000

@interface AppDelegate ()
{
    FirstScrollController *firstCol;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    firstCol=[[FirstScrollController alloc]init];
    //创建window
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [self InitJPush:launchOptions];
    
/**
 *  短信设置
 */
    [SMSSDK registerApp:SMSapp_Key withSecret:SMSapp_Secret];
    
    
    /***************************************分享开始**********************************************/
    
    [UMSocialData setAppKey:umeng_app_key];//设置友盟appkey
    //设置微信AppId，设置分享url，默认使用友盟的网址
    
    //    //设置支持没有客户端情况下使用SSO授权
    [UMSocialQQHandler setSupportWebView:YES];
    //打开调试log的开关
    [UMSocialData openLog:YES];
    
    //如果你要支持不同的屏幕方向，需要这样设置，否则在iPhone只支持一个竖屏方向
    [UMSocialConfig setSupportedInterfaceOrientations:UIInterfaceOrientationMaskAll];
    
    //设置微信AppId，设置分享url，默认使用友盟的网址
    [UMSocialWechatHandler setWXAppId:@"wxe327f26896695d54" appSecret:@"f89650b0ca9d9077ffc028715b4d6f6b" url:@"http://www.umeng.com/social"];
//
    
    
    //    //设置分享到QQ空间的应用Id，和分享url 链接
    [UMSocialQQHandler setQQWithAppId:@"1105165347" appKey:@"omWXy6xWRkhmj5Mn" url:@"http://www.umeng.com/social"];
    //    //设置支持没有客户端情况下使用SSO授权
    [UMSocialQQHandler setSupportWebView:YES];
    
    
    /***************************************分享结束**********************************************/
    
    
    
    MainViewController * mainViewController = [[MainViewController alloc] init];
    UINavigationController * navigationController = [[UINavigationController alloc] initWithRootViewController:mainViewController];
    
    [[UINavigationBar appearance] setBarTintColor:[UIColor orangeColor]];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    self.window.rootViewController = navigationController;
    
    
//    if (get_sp(@"memberid")==nil) {
    LoginViewController * loginVC=[[LoginViewController alloc] init];
    UINavigationController * LoginnavigationController = [[UINavigationController alloc] initWithRootViewController:loginVC];
    
    [[UINavigationBar appearance] setBarTintColor:[UIColor orangeColor]];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.window.rootViewController=LoginnavigationController;
//    }
//    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]) {
//     
//        MainViewController * mainViewController = [[MainViewController alloc] init];
//        UINavigationController * navigationController = [[UINavigationController alloc] initWithRootViewController:mainViewController];
//        self.window.rootViewController = navigationController;
//        
//    }
//    else
//    {
//        self.window.rootViewController =firstCol;
//        
//        [self.window makeKeyAndVisible];
//        //[self getAliPay];
//    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeRootView1:) name:@"changeRootView1" object:nil];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        NSString *alias = [NSString stringWithFormat:@"alias_%@",get_sp(@"id")];
//        NSSet * tags = [NSSet setWithObjects:[NSString stringWithFormat:@"tags_%@",get_sp(@"id")], nil] ;
//        [JPUSHService setTags:tags alias:alias callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
//    });
    
    [self clearBadge:application];

    return YES;
    
}

-(void)changeRootView1:(id)sender
{
    MainViewController * mainViewController = [[MainViewController alloc] init];
    UINavigationController * navigationController = [[UINavigationController alloc] initWithRootViewController:mainViewController];
    self.window.rootViewController = navigationController;
    NSString *alias = [NSString stringWithFormat:@"alias_%@",get_sp(@"merchantid")];
    NSSet * tags = [NSSet setWithObjects:[NSString stringWithFormat:@"tags_%@",get_sp(@"merchantid")], nil] ;
    [JPUSHService setTags:tags alias:alias callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
    return;
}


-(void)InitJPush:(NSDictionary *)launchOptions
{
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"fea118f5f54207d0ec7ace10"
                          channel:@"developer"
                 apsForProduction:0
            advertisingIdentifier:nil];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
}














/**
 *  Ping++ iOS 8 及以下
 *
 *  @param application       <#application description#>
 *  @param url               <#url description#>
 *  @param sourceApplication <#sourceApplication description#>
 *  @param annotation        <#annotation description#>
 *
 *  @return <#return value description#>
 */
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    BOOL canHandleURL = [Pingpp handleOpenURL:url withCompletion:nil];
    
    return canHandleURL;
    
}
/**
 *  Ping++ iOS 9 及以上
 *
 *  @param app     <#app description#>
 *  @param url     <#url description#>
 *  @param options <#options description#>
 *
 *  @return <#return value description#>
 */
- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url options:(NSDictionary *)options {
    
    BOOL canHandleURL = [Pingpp handleOpenURL:url withCompletion:nil];
    
    return canHandleURL;
    
}

#pragma mark- JPUSHRegisterDelegate
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    
    //    NSString *alias = ZY_NSStringFromFormat(@"driver_alias_%@",[ProjectTools getUserID]) ;
    //     NSSet * tags = [NSSet setWithObjects:ZY_NSStringFromFormat(@"driver_tags_%@",[ProjectTools getUserID]), nil] ;
    //        [JPUSHService setTags:tags alias:alias callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
    
    //    [JPUSHService setAlias:alias callbackSelector:@selector(tagsAliasCallback:tags:alias:)  object:self];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        NSDictionary *extras = [userInfo valueForKey:@"extras"];//服务端传递的Extras附加字段，key是自己定义的
        [self BuildOrderModelWithUserInfo:extras];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    
    NSDictionary *extras = [userInfo valueForKey:@"extras"];//服务端传递的Extras附加字段，key是自己定义的
    [self BuildOrderModelWithUserInfo:extras];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
    
    NSDictionary *extras = [userInfo valueForKey:@"extras"];//服务端传递的Extras附加字段，key是自己定义的
    [self BuildOrderModelWithUserInfo:extras];
}
#pragma mark- 接收自定义消息
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    //    NSString *content = [userInfo valueForKey:@"content"];
    NSDictionary *extras = [userInfo valueForKey:@"extras"];//服务端传递的Extras附加字段，key是自己定义的
    
    //pushType:1，出租车，2出租预约，3拼车，4系统
    [self BuildOrderModelWithUserInfo:extras];
}
-(void)BuildOrderModelWithUserInfo:(NSDictionary *)userInfo
{
    @try {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshOrderList" object:nil];
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
    
    
    
    
}
-(void)clearBadge:(UIApplication *)application
{
    
    [JPUSHService resetBadge];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
#pragma mark - launch
-(void)tagsAliasCallback:(int)iResCode
                    tags:(NSSet*)tags
                   alias:(NSString*)alias
{
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
